package com.leo.foodmaster.admin.foodMaterial.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.foodmaster.admin.foodMaterial.entity.FoodMaterial;
import com.leo.foodmaster.admin.foodMaterial.entity.FoodMaterialType;
import com.leo.foodmaster.admin.foodMaterial.mapper.FoodMaterialTypeMapper;
import com.leo.foodmaster.admin.foodMaterial.service.IFoodMaterialService;
import com.leo.foodmaster.admin.foodMaterial.service.IFoodMaterialTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leo.foodmaster.commons.entity.Result;
import com.leo.foodmaster.commons.util.WebUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Leo
 * @since 2021-07-14
 */
@Service
@AllArgsConstructor
public class FoodMaterialTypeServiceImpl extends ServiceImpl<FoodMaterialTypeMapper, FoodMaterialType> implements IFoodMaterialTypeService {
    private final IFoodMaterialService foodMaterialService;

    /**
     * 条件分页查询食材类型
     * @param page 分页参数
     * @param name 食材类型名称
     * @return IPage<FoodMaterialType>
     */
    @Override
    public IPage<FoodMaterialType> getFoodMaterialTypePageList(Page<FoodMaterialType> page, String name) {
        // 查询登录用户所在公司的食材类型列表
        Long organId = WebUtils.getUser().getOrganId();
        LambdaQueryWrapper<FoodMaterialType> qw = Wrappers.lambdaQuery(FoodMaterialType.class)
                .eq(FoodMaterialType::getOrganId, organId)
                .like(StrUtil.isNotBlank(name), FoodMaterialType::getName, name);
        return page(page, qw);
    }

    /**
     * 删除食材类型
     * @param foodMaterialTypeIds 食材类型Ids
     * @return Result<Object>
     */
    @Override
    public Result<Object> deleteFoodMaterialType(String foodMaterialTypeIds) {
        String[] idArray = foodMaterialTypeIds.split(StrUtil.COMMA);
        List<Long> idList = new ArrayList<>();
        for (String id : idArray) {
            // 如果有食材正在使用该食材类型，不能删除
            int count = foodMaterialService.count(Wrappers.lambdaQuery(FoodMaterial.class)
                    .eq(FoodMaterial::getTypeId, id));
            if (count != 0) {
                return Result.fail("有食材正在使用该类型，不能删除！");
            }
            idList.add(Long.parseLong(id));
        }
        removeByIds(idList);
        return Result.success();
    }

    /**
     * 新增食材分类
     * @param foodMaterialType 食材分类信息
     * @return boolean
     */
    @Override
    public boolean add(FoodMaterialType foodMaterialType) {
        Long organId = WebUtils.getUser().getOrganId();
        foodMaterialType.setOrganId(organId);
        return save(foodMaterialType);
    }
}
